﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SQLServerHealthCheck.Model;
using AG.Utilities;

namespace SQLServerHealthCheck.SQLServer.IssueTypes
{
    public class ServiceCheckTooManyBackupsOnTheSameDrive : IssueTypeCheckBase
    {
        public List<List<int>> databasenumbers = new List<List<int>>();
        public ServiceCheckTooManyBackupsOnTheSameDrive()
        {
            IssueTypeId = 2017;
        }

        public override void Check()
        {
            try
            {
                // Create a Data Context 
                HealthCheckDataContext dc = new HealthCheckDataContext(System.Configuration.ConfigurationManager.AppSettings["ConnectionStringSSHCDatabase"]);
                Issue issue;

                ThresholdValue numberOfBackups = dc.ThresholdValues.FirstOrDefault(t => t.IssueTypeID == IssueTypeId && t.ThresholdValueID == 1);

                List<int[]> dbs = new List<int[]>();

                var qry = from s in dc.Services
                          from d in s.Databases
                          from db in s.Databases
                          where d.LatestBackUpPath != null
                          && db.LatestBackUpPath != null
                          && (d.LatestBackUpPath.Remove(1)) == (db.LatestBackUpPath.Remove(1))
                          && d.DatabaseID < db.DatabaseID
                          &&
                          (
                            (d.LatestFullBackupStart >= db.LatestFullBackupStart
                            && d.LatestFullBackupStart <= db.LatestFullBackup)
                            ||
                            (d.LatestFullBackup >= db.LatestFullBackupStart
                            && d.LatestFullBackup <= db.LatestFullBackup)
                            ||
                            (d.LatestFullBackupStart >= db.LatestFullBackupStart
                            && d.LatestFullBackup <= db.LatestFullBackup)
                             ||
                            (d.LatestFullBackupStart <= db.LatestFullBackupStart
                            && d.LatestFullBackup >= db.LatestFullBackup)
                          )
                          select new
                          {
                              name = d.DatabaseName
                          ,
                              name2 = db.DatabaseName
                          ,
                              dbid = d.DatabaseID
                          ,
                              dbidb = db.DatabaseID
                          ,
                              serviceId = s.ServiceID

                          };

                var alldatabase = from databases in dc.Databases
                                  select databases;



                foreach (var item in qry)
                {
                    dbs.Add(new int[2] { item.dbid, item.dbidb });
                }



                if (dbs.Count > 0)
                {
                    getdblists(dbs);
                }
                for (int i = 0; i < databasenumbers.Count; i++)
                {




                    if (databasenumbers[i].Count < numberOfBackups.Value)
                    {
                        databasenumbers.RemoveAt(i);
                        i--;

                    }



                }




                foreach (var database in qry)
                {
                    foreach (var item in databasenumbers)
                    {

                        if (item.First() == (database.dbid) && item[1] == database.dbidb)
                        {
                            string dataname = "";
                            issue = new Issue();
                            IssueType issueType = dc.IssueTypes.FirstOrDefault(i => i.IssueTypeId == IssueTypeId);

                            issue.IssueType = issueType;
                            issue.TargetId = database.serviceId;

                            foreach (var databasesnames in alldatabase)
                            {
                                if (item.Count > 2)
                                {


                                    foreach (var number in item)
                                    {


                                        if (databasesnames.DatabaseID == number)
                                        {
                                            dataname = dataname + databasesnames.DatabaseName + ", ";
                                        }


                                    }

                                }
                                else
                                {
                                    if (databasesnames.DatabaseID == item[0])
                                    {
                                        dataname = dataname + databasesnames.DatabaseName;
                                    }
                                    if (databasesnames.DatabaseID == item[1])
                                    {
                                        dataname = dataname + ", " + databasesnames.DatabaseName + "  ";
                                    }


                                }

                            }
                            dataname = dataname.Remove(dataname.Length - 2, 2);
                            issue.Description = issueType.Description.Replace("{Database}", dataname);
                            dc.Issues.InsertOnSubmit(issue);
                            dc.SubmitChanges();
                        }

                    }






                }



            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }
        public void getdblists(List<int[]> a)
        {
            List<int> help = new List<int>();
            help.Add(a[0][0]);
            help.Add(a[0][1]);
            for (int s = 1; s < a.Count; s++)
            {
                if (a[s][0] == a[0][0])
                {

                    a.RemoveAt(s);
                }

            }
            a.RemoveAt(0);
            if (a.Count == 0)
            {
                databasenumbers.Add(help);
            }
            else
            {
                for (int s = 0; s < a.Count; s++)
                {

                    if (a[s][0] == help.Last())
                    {
                        help.Add(a[s][1]);
                        for (int v = 1; v < a.Count; v++)
                        {
                            if (a[v][0] == a[0][0])
                            {

                                a.RemoveAt(v);
                            }

                        }
                        a.RemoveAt(s);
                    }


                }
                if (a.Count != 0)
                {
                    databasenumbers.Add(help);
                    getdblists(a);
                }
                else
                {

                    databasenumbers.Add(help);
                }
            }





        }



    }
}
